#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

#ifdef WIN32
#include <windows.h>
#endif

const short multicast_port = 1234;
const int max_message_count = 10;

class sender
{
public:
  sender(boost::asio::io_service& io_service,
      const boost::asio::ip::address& multicast_address)
    : endpoint_(multicast_address, multicast_port),
      socket_(io_service, endpoint_.protocol()),
      timer_(io_service),
      message_count_(0),
	  ifs("movie/bigbuck.ts", std::ios::binary)
  {
    buf = new char[bufsize];

	if(!ifs.is_open())
	{
		std::cerr << "failed to open movie" << std::endl;
	}

    ifs.read(buf, bufsize);
	if(!ifs.good()) {
		std::cerr << "failed to read" << std::endl;
	}
    size_t bytes_read = ifs.gcount();

    socket_.async_send_to(
	boost::asio::buffer(buf, bytes_read), endpoint_,
        boost::bind(&sender::handle_send, this,
          boost::asio::placeholders::error));
  }

  ~sender()
  {
    delete [] buf;
  }

    void handle_send(const boost::system::error_code& error)
    {
    if (!error)
    {
#ifdef WIN32
		Sleep(2);
#else
		usleep(1000);
#endif
		ifs.read(buf, bufsize);

		if(!ifs.good()) {
			std::cerr << "failed to read" << std::endl;
		}
		
        size_t bytes_read = ifs.gcount();
		//std::cout << "bytes_read: " << bytes_read << std::endl;

        socket_.async_send_to(
            boost::asio::buffer(buf, bytes_read), endpoint_,
            boost::bind(&sender::handle_send, this,
              boost::asio::placeholders::error));
    }
    else
    {
        std::cerr << "error in handle_sen_to: " << error.message() << std::endl;
    }
  }

private:
  boost::asio::ip::udp::endpoint endpoint_;
  boost::asio::ip::udp::socket socket_;
  boost::asio::deadline_timer timer_;
  int message_count_;
  std::string message_;

  std::ifstream ifs;
  char* buf;
  enum { bufsize = 1400 }; // similar to what we get from VLC
};

int main(int argc, char* argv[])
{
  try
  {
    boost::asio::io_service io_service;
    sender s(io_service, boost::asio::ip::address::from_string("224.0.0.0"));
    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

